import { useEffect, useCallback } from 'react';
import { Step } from '../types';

export const useElementPicker = (
  setSteps: React.Dispatch<React.SetStateAction<Step[]>>
) => {
  // 监听元素选择变化
  useEffect(() => {
    const handleStorageChange = async (changes: {
      [key: string]: chrome.storage.StorageChange;
    }) => {
      if (changes.selectedElementSelector) {
        const selector = changes.selectedElementSelector.newValue;
        
        if (selector) {
          console.log("🔄 检测到新的元素选择:", selector);
          
          const result = await chrome.storage.local.get(["pickingElementForStep"]);
          const stepIndex = result.pickingElementForStep;
          
          if (stepIndex !== undefined) {
            console.log("📍 更新步骤:", stepIndex, "选择器:", selector);
            
            setSteps((prevSteps) => {
              const newSteps = [...prevSteps];
              if (newSteps[stepIndex]) {
                newSteps[stepIndex].element = selector;
                chrome.storage.local.set({ tourSteps: newSteps });
              }
              return newSteps;
            });

            chrome.storage.local.remove([
              "pickingInProgress",
              "pickingElementForStep",
              "selectedElementSelector",
            ]);
          }
        }
      }
    };

    chrome.storage.onChanged.addListener(handleStorageChange);

    return () => {
      chrome.storage.onChanged.removeListener(handleStorageChange);
    };
  }, [setSteps]);

  // 启动元素选择器
  const startElementPicker = useCallback(async (stepIndex: number) => {
    try {
      const [tab] = await chrome.tabs.query({
        active: true,
        currentWindow: true,
      });
      if (!tab.id) return;

      await chrome.storage.local.set({
        pickingElementForStep: stepIndex,
        pickingInProgress: true,
      });

      chrome.tabs.sendMessage(
        tab.id,
        { action: "startElementPicker" },
        (response) => {
          // 这里不需要等待响应
        }
      );
    } catch (error) {
      console.error("启动元素选择器失败:", error);
    }
  }, []);

  // 获取用户选中的元素
  const getSelectedElement = useCallback(async (): Promise<string | null> => {
    try {
      const [tab] = await chrome.tabs.query({
        active: true,
        currentWindow: true,
      });
      if (!tab.id) return null;

      const response = await chrome.tabs.sendMessage(tab.id, {
        action: "getSelectedElement",
      });
      return response?.selector || null;
    } catch (error) {
      console.error("获取选中元素失败:", error);
      return null;
    }
  }, []);

  return {
    startElementPicker,
    getSelectedElement,
  };
};